package com.baize.baizeapp.test.mohu

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.os.Environment
import android.os.Handler
import android.util.Log
import android.view.PixelCopy
import android.view.View
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.lang.ref.WeakReference


object ScreenShotImageHelper {

    var bitmapRecerence: WeakReference<Bitmap>? = null

    fun generateScreenBlurBg(activity: Activity, scale: Int = 20, blurRadio: Int = 8) {
        if (activity.window == null) {
            return
        }
        val scaleBitmap = getBitmapFromView(activity.window.decorView,blurRadio)
//        val blurBitmap = FastBlurUtil.doBlur(getBitmapFromView(activity.window.decorView, scale), blurRadio, false)
        bitmapRecerence = WeakReference(scaleBitmap)
        saveBitmapForDask(scaleBitmap)
    }

    /**
     * 获取Bitmap背景
     */
    fun getScreenBlurBg(): Bitmap? {
        return bitmapRecerence?.get() ?: getBitmapWithDisk()
//        return if (bitmapRecerence?.get() != null) {
//            bitmapRecerence?.get()
//        } else getBitmapWithDisk()
    }

    private fun saveBitmapForDask(bitmap: Bitmap) {
        val format = CompressFormat.JPEG
        val quality = 100
        var stream = FileOutputStream(
            Environment.getExternalStorageDirectory().getPath().toString() + "/" + "screen_blur.jpg"
        )
        bitmap.compress(format, quality, stream)
        try {
            stream.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            stream.close()
        }
    }

    private fun getBitmapWithDisk(): Bitmap? {
        try {
            return BitmapFactory.decodeStream(
                FileInputStream(
                            Environment . getExternalStorageDirectory().getPath()
                        .toString() + "/" + "screen_blur.jpg"
                )
            )
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 获取ViewBitmap
     * @param scale 缩放比
     */
    fun getBitmapFromView(view: View, scale: Int): Bitmap {
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        val scaleBitmap =
            Bitmap.createScaledBitmap(bitmap, bitmap.width / scale, bitmap.height / scale, false)
        Log.i("yanze", "size:${bitmap.byteCount / 1024}  scale：${scaleBitmap.byteCount / 1024}")
        return scaleBitmap
    }

    private fun getBitmapFromView(view: View, activity: Activity, callback: (Bitmap) -> Unit) {
        activity.window?.let { window ->
            val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
            val locationOfViewInWindow = IntArray(2)
            view.getLocationInWindow(locationOfViewInWindow)
            try {
                PixelCopy.request(
                    window,
                    Rect(
                        locationOfViewInWindow[0],
                        locationOfViewInWindow[1],
                        locationOfViewInWindow[0] + view.width,
                        locationOfViewInWindow[1] + view.height
                    ),
                    bitmap,
                    { copyResult ->
                        if (copyResult == PixelCopy.SUCCESS) {
                            callback(bitmap)
                        }
                        // possible to handle other result codes ...
                    },
                    Handler()
                )
            } catch (e: IllegalArgumentException) {
                // PixelCopy may throw IllegalArgumentException, make sure to handle it
                e.printStackTrace()
            }
        }
    }

}